package org.dval.plugin.ioc;

import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@SuppressWarnings("unchecked")
public class IocKit {
    private IocKit() {
    }

    private static ConcurrentMap<String, IocObject> beanMap;

    public static void init(ConcurrentMap<String, Object> beanMap) {
        IocKit.beanMap = new ConcurrentHashMap<>();
        if (beanMap == null || beanMap.isEmpty()) {
            return;
        }
        for (String key : beanMap.keySet()) {//初始化时还是未知字段所以为空
            IocKit.beanMap.put(key, new IocObject(beanMap.get(key), null));
        }

    }

    public static ConcurrentMap<String, IocObject> getBeanMap() {
        return beanMap;
    }

    public static <T> T getBean(Class<?> clazz) {
        String beanName = clazz.getName();
        IocObject target = beanMap.get(beanName);
        if (target == null){
            return null;
        }
        return (T) target.getTarget();
    }

    public static <T> T getFields(Class<?> clazz) {
        String beanName = clazz.getName();
        IocObject target = beanMap.get(beanName);
        if (target == null){
            return null;
        }
        return (T) target.getFields();
    }

    public static void saveBean(Class<?> clazz, List<Field> fields) {
        String beanName = clazz.getName();
        if (beanMap.get(beanName) == null){
            return;
        }
        beanMap.get(beanName).setFields(fields);
    }
}

class IocObject {
    private Object target;
    private List<Field> fields;

    public List<Field> getFields() {
        return fields;
    }

    public void setFields(List<Field> fields) {
        this.fields = fields;
    }

    public IocObject(Object target, List<Field> fields) {
        this.target = target;
        this.fields = fields;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }
}